<template>
	<el-container v-loading="loading">
		<el-header>
			<div class="left-panel">
				<ex-select @change="changeSelect" clearable  v-model="userStatus" dict-code="EMPLOYEE_STATUS"></ex-select>
				<fsButton style="margin-left: 5px;" ref="button" plain size="small" :buttons="buttons" @clickHandler="buttonHandler"></fsButton>
			</div>
			<div class="right-panel">
				<ex-search ref="search" size="small" :searches="searches" default-code="userName" placeholder="请输入员工姓名" @searchOk="searchHandler"></ex-search>
			</div>
		</el-header>
		<el-main class="nopadding" style="padding: 0 5px;">
			<el-table ref="table" :data="tableDatas"
					  row-key="id"
					  :border=true
					  :height="this.tableHeight"
					  :key="elKey"
					  :stripe=true>
				<el-table-column type="expand">
					<template #default="props">
						<div style="margin: 0 35px 0 35px;">
							<ex-table :columns="assetColumns" :height="0" :selection="false" :url="this.$API.asset.asset.list.url" :params="{usingMenId:props.row.id,excludeStatus:['delete']}" @columnClick="columnClickHandler"></ex-table>
						</div>
					</template>
				</el-table-column>
				<template v-for="column in this.columns" :key="column.code">
					<el-table-column :prop="column.code"
									 :label="column.name"
									 :sortable="column.sortable?column.sortable:false"
									 :formatter="this.formatters"
									 :column-key="column.code"
									 :summary = "column.summary? column.summary:false"
									 :show-overflow-tooltip="true"
									 :width="column.width?column.width:null">
					</el-table-column>
				</template>
			</el-table>
			<el-pagination ref="pagination"
						   v-model:current-page="pageForm.current"
						   v-model:page-size="pageForm.pageSize"
						   :page-sizes="[30,50,100]"
						   :small="true"
						   :hide-on-single-page="false"
						   background
						   layout="->,total, jumper, sizes, prev, pager, next"
						   :total="total"
						   @size-change="handleSizeChange"
						   @current-change="handleCurrentChange"
						   style="margin: 0 0 0 0;padding: 8px 0px;">
			</el-pagination>
		</el-main>
	</el-container>
	<data-card ref="dataCard"></data-card>
</template>

<script>
import ExTable from "@/components/exTable/index.vue";
import ExSearch from "@/components/exSearch/index.vue";
import ExTreeNavigation from "@/components/exSearchTree/index.vue";
import ExSearchTree from "@/components/exSearchTree/index.vue";
import scSelectFilter from "@/components/scSelectFilter/index.vue";
import tool from "@/utils/tool";
import DataCard from "@/views/asset/card/card.vue";
import ExSelect from "@/components/exSelect/index.vue";
import globalparam from "@/constant/model/globalparam";
import {h} from "vue";
import {ElButton, ElContainer} from "element-plus";
export default {
	name: '员工资产统计报表',
	components: {
		ExSelect,
		DataCard,
		scSelectFilter,
		ExSearchTree,
		ExTreeNavigation,
		ExSearch,
		ExTable,
	},
	data() {
		return {
			dialog: {
				save: false,
				permission: false,
			},
			apiObj: [],
			buttons: [
				{name: "导出", icon: "el-icon-download", click: "export", type: "info", permission: "export"},
			],
			searches: [
				{type: "input", name: "员工姓名", code: "userName", placeholder: "请输入员工姓名"},
				{type: "input", name: "员工编号", code: "userCode", placeholder: "请输入员工编号"},
				{type: "tree-select", name: "所属部门", code: "deptIds", placeholder: "请选择所属部门", dictCode:'SysOrganization',checkStrictly:true,multiple:true,dataPermissionProcess:true,permissionData:this.$TOOL.current.readDeptIds()},
			],
			columns: [
				{code: "userCode", name: "员工编号", width:"",sortable:true},
				{code: "userName", name: "员工姓名", width:"",sortable:true},
				// {code: "userStatus", name: "员工状态", width:"100",formatter:function (row,value,_this){
				// 		if(!row.userStatus){
				// 			return "离职";
				// 		}else{
				// 			return value;
				// 		}
				// 	}},
				{code: "userStatus", name: "员工状态", width:"100",formatter:"DICT",key: "EMPLOYEE_STATUS"},
				{code: "orgId", name: "所属部门", width:"",sortable:true,formatter: "DICT",key: "SysOrganization"},
				{code: "mobile", name: "用户手机号", width:"",sortable:true},
				{code: "email", name: "用户邮箱", width:"",sortable:true},
			],
			assetColumns: [
				{code: "assetStatusId", name: "资产状态", width:"75",formatter:"DICT",key: "ASSET_STATUS"},
				{code: "code", name: "资产编码", width:"135",click:"show1"},
				{code: "financialCode", name: "财务编码", width:"170"},
				{code: "assetCategoryId", name: "资产分类",width:"150", formatter:"DICT",key: "FamsAssetCategory"},
				{code: "name", name: "资产名称", width:"200"},
				{code: "other.financialType", name: "账务类型",width: "75", formatter:"DICT",key: "FINANCIAL_TYPE"},
				{code: "brand", name: "品牌", width:""},
				{code: "model", name: "规格型号", width:""},
				{code: "serialCode", name: "资产序列号", width:"150"},
				{code: "assetCount", name: "数量", width:"80",summary:true,formatter:'NUMBER'},
				{code: "originalValue", name: "原值", width:"100",summary:true,formatter:'MONEY'},
				{code: "netValue", name: "净值", width:"100",summary:true,formatter:'MONEY'},
				{code: "usingMenId", name: "使用人", width:"80",formatter: "DICT",key: "SysUser"},
				{code: "usingDepartmentId", name: "使用部门", width:"100",formatter: "DICT",key: "SysOrganization"},
				{code: "storePlaceId", name: "资产位置",width: "120", formatter:"DICT",key: "FamsPosition"},
			],
			userStatus: '',
			assetIds:[],
			pageForm: {
				current: 1,
				pageSize: 30,
			},
			total: 0,
			elKey: 0,
			tableHeight:0,
			pathCodeMap:{},
			tableDatas: [],
			assetTableDatas: [],
			excludeStatus:['delete'],
			readDeptIds: this.$TOOL.current.readDeptIds(),
			// manageDeptIds: this.$TOOL.current.manageDeptIds(),
			manageAssetCategoryIds: this.$TOOL.current.manageAssetCategoryIds(),
			assetStatisticsRange: "",
			loading: false,
			loginUsers: tool.current.user(),
		}
	},
	created() {
	},
	mounted() {
		this.resetTableHeight();
		window.addEventListener("resize", this.resetTableHeight);
		this.loadData();
	},
	beforeMount() {
	},
	beforeUnmount() {
		window.removeEventListener("resize", this.resetTableHeight);
	},
	methods: {
		buttonHandler(index, name) {
			this.$options.methods[name](this, index);
		},
		resetTableHeight() {
			let height = this.$refs.table.$parent.$el.clientHeight - 40;
			if (height <= 300) {
				this.tableHeight = 300;
			} else {
				this.tableHeight = height;
			}
			if(!this.tableHeight){
				this.tableHeight = 200;
			}
		},
		async searchHandler() {
			this.loadData();
		},
		columnClickHandler(name,data){
			this.$options.methods[name](this, data);
		},
		changeSelect(){
			this.loadData();
		},
		loadData(){
			let queryParams = {};
			this.loading = true;
			//释放搜索组件的loading状态
			if (this.$refs.search) {
				this.$refs.search.setLoading(true);
			}
			this.$refs.search.drawer=false;
			this.fomateQueryParams(queryParams,this);
			queryParams = Object.assign(queryParams, this.pageForm);
			this.$API.asset.assetSummaryStatistics.countOperatorByAssetPage.post(queryParams).then((rsp =>{
				if(rsp.code === 2000){
					this.tableDatas = rsp.data.records;
					this.pageForm.current = rsp.data.current;
					this.pageForm.pageSize = rsp.data.size;
					this.total = rsp.data.total;
					this.elKey++;
				}
				//释放搜索组件的loading状态
				if (this.$refs.search) {
					this.$refs.search.setLoading(false);
				}
				this.loading = false;
			}));
		},
		//查看
		async show1(_this, row) {
			let assetCategory = await _this.$cache.data.loadAssetCategory(row.assetCategoryId);
			try {
				_this.loading = true;
				let entity = {cardId: assetCategory.assetCardId, _editFlag: false}
				_this.$nextTick(() => {
					_this.cardPreview = false;
					_this.$refs.dataCard.open(Object.assign(entity, row));
				});
			} finally {
				_this.loading = false;
			}
		},
		//导出
		async export(_this,index) {
			_this.$refs.button.loading(index, true);
			let queryPrams = {};
			_this.fomateQueryParams(queryPrams,_this);
			queryPrams.exportType = "employeeSummary";
			let res = await _this.$API.asset.assetSummaryStatistics.export.post(queryPrams);
			if (res.code === 2000) {
				await _this.$alert(_this.$t('common.export_request_success'), "提示", {type: 'success'}).catch(()=>{});
			}
			_this.$refs.button.loading(index, false);
		},
		formatters(row, column, cellValue, index) {
			for (const item of this.columns) {
				if (item.code === column.property){
					if (item.click) {
						if (item.fixedValue) {
							cellValue = item.fixedValue;
						} else {
							if (item.formatter) {
								if (item.formatter instanceof Function) {
									cellValue = item.formatter(row, cellValue, this);
								} else {
									cellValue = tool.format.convert(cellValue, item.formatter, item.key);
								}
							}
						}
						let label = cellValue+'';
						let clicks = item.click.split(',');
						let labels = label.split(',');
						let permissions = [];
						if (item.permissions) {
							permissions = item.permissions.split(',');
							// permissions.splice(permissions.indexOf(''), 1);
						}
						let children = [];
						clicks.forEach((click, index) => {
							let elBtn = h(ElButton, {
								link: true,
								type: 'primary',
								style: {margin: 'auto'},
								size: 'small',
								["onClick"]: () => {
									this.$options.methods[click](this, row);
									// this.$emit('columnClick', click, row);
								}
							}, () => labels[index])
							if (permissions.length > 0) {
								if (permissions.filter(item => item === click).length > 0) {
									children.push(elBtn);
								}
							} else {
								children.push(elBtn);
							}
						});
						// cellValue = h(ElButton,{link:true,type:'primary',size:'small',["onClick"]:()=>{ this.$emit('columnClick',item.click,row);}},()=>label);
						cellValue = h(ElContainer, {key: tool.uuid("elk"), style: {display: 'flex'}}, () => children);
					}else{
						if (item.formatter) {
							if (item.formatter instanceof Function) {
								cellValue = item.formatter(row, cellValue, this, index);
							} else {
								cellValue = tool.format.convert(cellValue, item.formatter, item.key);
							}
						}
					}
				}

			}
			return cellValue;
		},
		searchAsset(item,queryParams) {
			let title = "公司汇总统计"+item+"资产明细";
			//跳转到搜索台账页面
			let fromRouteId = this.$TOOL.crypto.MD5(this.$route.path);//当前页面的路由地址
			let key = this.$TOOL.crypto.MD5(item);//可以做为key的关键字段或内容
			/**
			 *  1 = 根据管理部门，根据登录账户管理范围，资产的管理部门在账户管理范围内的显示<br>
			 *  2 = 根据使用部门，根据登录账户管理范围，资产的使用部门在账户管理范围内的显示<br>
			 *  3 = 根据管理部门或使用部门，根据登录账户管理范围，资产的使用部门或管理部门在账户管理范围内的显示<br>
			 *  其它 = 根据管理部门，按台账，根据使用部门或管理部门或借用部门在管理范围内的
			 */
				//设置搜索参数
			let routeParams = {
					id: key,
					title: title,
					showXuli: true,
					fixedParams:{
						assetStatisticsRange:queryParams.assetStatisticsRange,
						deptIds:queryParams.deptIds,
						assetCategoryIds:queryParams.assetCategoryIds
					},//固定搜索参数，打开页面后，用户通过搜索界面的清空按钮无法清除
					searchParams: queryParams
				};
			this.$store.dispatch("addRouteParams", routeParams);
			this.$router.push({
				name: "toAssetList",
				params: {fromRouteId: fromRouteId, key: key}
			});
		},
		fomateQueryParams(queryParams,_this){
			Object.assign(queryParams, _this.$refs.search.searchParams());
			if(_this.userStatus){
				queryParams.userStatus = _this.userStatus
			}
			if(!queryParams.deptIds||queryParams.deptIds.length===0){
				queryParams.deptIds = _this.readDeptIds;
			}
			if(!queryParams.assetCategoryIds||queryParams.assetCategoryIds.length===0){
				queryParams.assetCategoryIds = _this.manageAssetCategoryIds;
			}
			queryParams.excludeStatus = _this.excludeStatus;
		},
		handleSizeChange(pageSize) {
			this.pageForm.pageSize = pageSize;
			this.loadData();
		},
		handleCurrentChange(currentPage) {
			this.pageForm.current = currentPage;
			this.loadData();
		},
	}
}

</script>
<style scoped>

</style>
